#!/bin/bash -xe

kata_coco_top_dir="$HOME/workspace/CoCo"

guest_components_repo_url="https://gitee.com/hanliyang-kata-coco/guest-components.git"
guest_components_repo_branch="0.10.0-hygon-arch-sig"
guest_components_repo_dir=${kata_coco_top_dir}/guest-components

if [ ! -e $guest_components_repo_dir ]; then
  git clone ${guest_components_repo_url} \
    -b ${guest_components_repo_branch} \
    ${guest_components_repo_dir}
fi

install_coco_guest_components_deps () {
  echo "[Install coco guest-components dependencies]"
  sudo yum install -y perl \
    perl-FindBin perl-IPC-Cmd
}

install_coco_guest_components_deps

build_aa () {
  echo "[Build AA (Attestation-Agent)]"
  pushd ${guest_components_repo_dir}/attestation-agent/
  make ttrpc=true ATTESTER=csv-attester
  popd
}

build_aa

build_cdh () {
  echo "[Build CDH (Confidential-Data-Hub)]"
  pushd ${guest_components_repo_dir}/confidential-data-hub/
  make
  popd
}

build_cdh

build_api_server_rest () {
  echo "[Build api-server-rest]"
  pushd ${guest_components_repo_dir}/api-server-rest/
  make
  popd
}

build_api_server_rest

install_coco_guest_components_tarball () {
  local coco_guest_components_tarball="/dev/shm/guest-components.tar.xz"

  echo "[Install ${coco_guest_components_tarball}]"
  rm -rf ${coco_guest_components_tarball}

  pushd ${guest_components_repo_dir}/target/x86_64-unknown-linux-gnu/release/
  cp ${guest_components_repo_dir}/confidential-data-hub/storage/scripts/luks-encrypt-storage \
    ./
  tar --transform="s/^/usr\/local\/bin\//" \
    -cvJf ${coco_guest_components_tarball} \
    api-server-rest \
    attestation-agent \
    confidential-data-hub \
    luks-encrypt-storage
  popd # .../release
}

install_coco_guest_components_tarball
